﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SQLDeploy.Data.Deployment.Steps.Tasks
{
    public class _FileBasedTask : _BaseTask
    {
        public _FileBasedTask(Step parentStep) : base(parentStep) { }

        public _FileBasedTask(Step parentStep, string name, string connectionName) :
            base(parentStep, name, connectionName) { }

        public _FileBasedTask(Step parentStep, string name, string connectionName, string file) :
            base(parentStep, name, connectionName)
        {
            fileName = file;
        }

        private string _filename;

        protected internal string fileName
        {
            get { return fileName; }
            set
            {
                if (value == null)
                    throw new ArgumentNullException("fileName cannot be null");
                if (_filename == null ||
                    !Internal.Shared.DefaultStringComparer().Equals(_filename, value))
                {
                    _filename = value;
                }
            }
        }

        public override bool performValidation()
        {
            if (fileName == null)
                return false;
            if (!File.Exists(fileName))
            {
                Trace.TraceError("{0}{1} does not exist.", TaskNameHeader, fileName);
                return false;
            }
            try
            {
                return additionalFileChecks();
            }
            catch (Exception e)
            {
                Trace.TraceError("{0}{1}", TaskNameHeader, e.Message);
                return false;
            }
            
        }

        /// <summary>
        /// Override this method to perform additional checks on the file, if needed
        /// </summary>
        /// <returns>true if additional checks are successfull, output failures to Trace.TraceError("%Failure Message%") prior to returning false, throwing any exception will force a false to be returned and the Exception message will be traced.</returns>
        protected internal virtual bool additionalFileChecks()
        {
            return true;
        }

    }
}
